#include <pcapgether.h>
#include <requesthandler.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <iostream>

using namespace std;

extern InOutCount Count;

int comminit()
{
	int sockfd;
	struct sockaddr_un serveraddr;

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sockfd < 0)
	{
		perror("socket error : ");
		exit(1);
	}

	unlink("/tmp/jstg");
	bzero(&serveraddr, sizeof(serveraddr));
	serveraddr.sun_family = AF_UNIX;
	strcpy(serveraddr.sun_path, "/tmp/jstg");

	if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
	{
		perror("bind error :");
		exit(0);
	}

	if(listen(sockfd, 5) ==-1)
	{
		perror("listen error :");
		exit(0);
	}
	return sockfd;
}

int acceptor(int sockfd)
{
	int client_sockfd, clilen;
	struct sockaddr_un clientaddr;

	clilen = sizeof(clientaddr);
	client_sockfd = accept(sockfd, (struct sockaddr *)&clientaddr,
										(socklen_t *)&clilen);
	return client_sockfd;
}

void *requesthandler(void *data)
{
	int ret;
	int n;
	char readbuf[1024];
	char writebuf[1024]; 
	int client_sockfd = *(int *)data; 

	while(1)
	{
		memset(readbuf, 0x00, sizeof(readbuf));
		if ((n = read(client_sockfd, readbuf, 1024)) <= 0)
		{
			perror("Read Error");
			close(client_sockfd);
			break;
		}

		if (strncmp(readbuf, "quit", 4) == 0)
		{
			close(client_sockfd);
			break;
		}
		ret = requesttrans(readbuf, writebuf);
		write(client_sockfd, writebuf,1024);
	}
	pthread_exit(0);
}

int requesttrans(char *readbuf, char *writebuf)
{
	sprintf(writebuf, "%d\t%d\t%d\t%d", Count.inbps, Count.outbps, 
											Count.inpps, Count.outpps);
	return 1;
}
